use std::{
    sync::{mpsc, Arc, Mutex},
    thread::{self, JoinHandle},
};

/**
 * 工作结构
 */
pub struct Worker {
    id: usize,
    thread: Option<JoinHandle<()>>,
}
impl Worker {
    /**
     * 构造方法
     */
    pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        //thread::spawn() 会在系统资源不够时创建失败并painc
        //更加安全的线程创建
        let thread_builder = thread::Builder::new();
        let thread = thread_builder
        .spawn(move || loop {
            let message = receiver.lock().unwrap().recv();

            match message {
                Ok(job) => {
                    println!("Worker {id} got a job; executing.");

                    job();
                }
                Err(_) => {
                    println!("Worker {id} disconnected; shutting down.");
                    break;
                }
            }
        })
        .unwrap();
        Worker {
            id: id,
            thread: Some(thread),
        }
    }
}
/**
 * 具体工作闭包
 */
type Job = Box<dyn FnOnce() + Send + 'static>;

/**
 * 线程池
 */
pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}

impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);
        // 创建通信信道
        let (sender, receiver) = mpsc::channel();
        //分配空间，并没有填充元素
        let mut workers = Vec::with_capacity(size);
        // 创建共享的安全接收者
        let receiver_safe = Arc::new(Mutex::new(receiver));
        for id in 0..size {
            //创建线程
            workers.push(Worker::new(id, Arc::clone(&receiver_safe)));
        }

        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }
    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}
impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);
            //将worker的值移动出来并替换为none，对移动出来的线程进行清除
            worker.thread.take().unwrap().join().unwrap();
        }
    }
}
